package de.htw.praxisprojekt.algo.impl;

import java.util.List;

import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;

import de.htw.praxisprojekt.AlgoData;
import de.htw.praxisprojekt.Vector2D;
import de.htw.praxisprojekt.algo.LineAlgorithm;
import de.htw.praxisprojekt.data.AlgoPoint;
import de.htw.praxisprojekt.data.draw.DrawLine;
import de.htw.praxisprojekt.data.draw.DrawObject;
import de.htw.praxisprojekt.data.draw.DrawRing;

public class DistanceAlgorithm extends LineAlgorithm{

	private JSpinner distanceValue;
	private JCheckBox finalPoint;

	@Override
	public String getAlgoName(){
		return "Distanz";
	}

	@Override
	public JPanel getOptionPane(){
		JPanel panel=super.getOptionPane();
		panel.add(new JLabel("Distanz"));
		panel.add(distanceValue=new JSpinner(new SpinnerNumberModel(60.0,0.0,1000,1)));
		addChangeListenerToSpinner(distanceValue);
		panel.add(new JLabel("Endpunkt"));
		panel.add(finalPoint=new JCheckBox());
		addChangeListenerToCheckBox(finalPoint);

		panel.add(new JLabel());
		panel.add(new JLabel());

		panel.add(new JLabel());
		panel.add(new JLabel());

		return panel;
	}

	@Override
	public void play(AlgoData algoData,int maxStepIndex){
		super.play(algoData,maxStepIndex);
		List<AlgoPoint> algoPoints=algoData.getAlgoPoints();
		List<DrawObject> drawObjects=algoData.getDrawObjects();
		int stepIndex=0;
		float distance=((Double)distanceValue.getValue()).floatValue()*algoData.getScaleFactor();
		boolean isFinalPoint=finalPoint.isSelected();

		int activeIndex=0;
		int nextIndex=1;
		while(nextIndex<algoPoints.size()&&stepIndex<maxStepIndex){
			Vector2D activePoint=algoPoints.get(activeIndex).getPoint();
			Vector2D nextPoint=algoPoints.get(nextIndex).getPoint();
			if(stepIndex==maxStepIndex-1)
				drawObjects.add(new DrawRing(activePoint,distance*2));
			if(activePoint.dist(nextPoint)>=distance){
				drawObjects.add(new DrawLine(activePoint,nextPoint));
				activeIndex=nextIndex;
				nextIndex++;
			}else{
				nextIndex++;
			}
			stepIndex++;
		}
		if(isFinalPoint&&algoPoints.size()>0){
			nextIndex--;
			Vector2D activePoint=algoPoints.get(activeIndex).getPoint();
			Vector2D nextPoint=algoPoints.get(nextIndex).getPoint();
			drawObjects.add(new DrawLine(activePoint,nextPoint));
		}
		setStepIndex(stepIndex);
	}
}